package com.zhenhao.xsq.netsdk_demo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.sdk.AlarmMessCallBackV30;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.zhenhao.xsq.R;
import com.zhenhao.xsq.view.MySeekBar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timerulers.yongxiang.com.timerulerslib.views.RecordDataExistTimeSegment;
import timerulers.yongxiang.com.timerulerslib.views.TimebarView;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class GSYVideoPlayActivity extends AppCompatActivity {


    @BindView(R.id.timebar_zoom_out_btn)
    Button timebarZoomOutBtn;
    @BindView(R.id.current_time_tv)
    TextView currentTimeTv;
    @BindView(R.id.timebar_zoom_in_btn)
    Button timebarZoomInBtn;
    @BindView(R.id.zoom_layout)
    LinearLayout zoomLayout;
    @BindView(R.id.day)
    Button day;
    @BindView(R.id.hour)
    Button hour;
    @BindView(R.id.minute)
    Button minute;
    @BindView(R.id.videoPlayer)
    StandardGSYVideoPlayer videoPlayer;
    @BindView(R.id.my_timebar_view)
    TimebarView mTimebarView;
    @BindView(R.id.seek_progress)
    MySeekBar seekProgress;


    private String TAG = "GSYVideoPlayActivity";
    OrientationUtils orientationUtils;

    private int recordDays = 7;
    private long currentRealDateTime = System.currentTimeMillis();
    private Calendar calendar;

    private static long ONE_MINUTE_IN_MS = 60 * 1000;
    private static long ONE_HOUR_IN_MS = 60 * ONE_MINUTE_IN_MS;
    private static long ONE_DAY_IN_MS = 24 * ONE_HOUR_IN_MS;

    private SimpleDateFormat zeroTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private boolean isTouchSeeked = false;

    private final int PROGRESS_SEEEKTO = 100001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gsyvideo_play);
        ButterKnife.bind(this);

        //硬解码：1、打开，0、关闭
//mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
//软解码：1、打开，0、关闭
//mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "videotoolbox", 0);

//rtsp设置 https://ffmpeg.org/ffmpeg-protocols.html#rtsp
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp");
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_flags", "prefer_tcp");
//
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "allowed_media_types",
//        "video"); //根据媒体类型来配置
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", 20000);
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 1316);
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "infbuf", 1);  // 无限读
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 100L);
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240L);
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1L);
////  关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0L);
//        mMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1L);

        VideoOptionModel videoOptionModel =
                new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp");
        List<VideoOptionModel> list = new ArrayList<>();
        list.add(videoOptionModel);
        GSYVideoManager.instance().setOptionModelList(list);
//        String s = "rtsp://192.168.8.127:554/unicast/c2/s0/live";
        String s = "rtsp://admin:@kongchunbo0@192.168.8.127:554/unicast/c2/s0/live";
//        String s = "rtsp://admin:@kongchunbo0@192.168.8
//        .127:554/c2/b1725596308/e1725607191/replay/s0/";
//        String s = "rtsp://admin:@kongchunbo0@192.168.8
//        .127:554/c2/b1725724800/e1725872009/replay/s0/";
//        String time1 = TimeUtil.timesTamp2Year(1725724800000l);
//        String time2 = TimeUtil.timesTamp2Year(1725872009000l);
//        long temp = 1725607191-1725596308;
//        Log.e(TAG, "" + time1 + "," + time2+","+temp);
        videoPlayer.setUp(s, true, "title");

        //增加封面
        /*ImageView imageView = new ImageView(this);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setImageResource(R.mipmap.xxx1);
        videoPlayer.setThumbImageView(imageView);*/
        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        //设置旋转
        orientationUtils = new OrientationUtils(this, videoPlayer);
        //设置全屏按键功能,这是使用的是选择屏幕，而不是全屏
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
                // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
                orientationUtils.resolveByClick();
                //finish();
            }
        });
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(true);
        //设置返回按键功能
        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

//        videoPlayer.startPlayLogic();

        initTimeView();
    }

    private void initTimeView() {
        calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        //long timebarLeftEndPointTime = currentRealDateTime - 7 * 24 * 3600 * 1000;
        long timebarLeftEndPointTime = calendar.getTimeInMillis();
        System.out.println("calendar:" + calendar.getTime() + "  currentRealDateTime:" + currentRealDateTime);

        calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        long timebarRightEndPointTime = calendar.getTimeInMillis();
        System.out.println("calendar:" + calendar.getTime() + "  currentRealDateTime:" + currentRealDateTime);

        mTimebarView.initTimebarLengthAndPosition(timebarLeftEndPointTime,
                timebarRightEndPointTime - 1000, currentRealDateTime);

        final List<RecordDataExistTimeSegment> recordDataList = new ArrayList<>();
        recordDataList.add(new RecordDataExistTimeSegment(timebarLeftEndPointTime - ONE_HOUR_IN_MS * 1, timebarLeftEndPointTime + ONE_HOUR_IN_MS * 3));
        recordDataList.add(new RecordDataExistTimeSegment(timebarLeftEndPointTime + ONE_HOUR_IN_MS * 4, timebarLeftEndPointTime + ONE_HOUR_IN_MS * 8));
        recordDataList.add(new RecordDataExistTimeSegment(timebarLeftEndPointTime + ONE_HOUR_IN_MS * 12, timebarLeftEndPointTime + ONE_HOUR_IN_MS * 19));
        recordDataList.add(new RecordDataExistTimeSegment(timebarLeftEndPointTime + ONE_HOUR_IN_MS * 20, timebarRightEndPointTime));

        mTimebarView.setRecordDataExistTimeClipsList(recordDataList);

        mTimebarView.openMove();
        mTimebarView.checkVideo(true);

        //刻度条移动监听
        mTimebarView.setOnBarMoveListener(new TimebarView.OnBarMoveListener() {
            @Override
            public void onBarMove(long screenLeftTime, long screenRightTime, long currentTime) {
                if (currentTime == -1) {
                    Toast.makeText(GSYVideoPlayActivity.this, "当前时刻没有录像", Toast.LENGTH_SHORT).show();
                }
                currentTimeTv.setText(zeroTimeFormat.format(currentTime));
            }

            @Override
            public void OnBarMoveFinish(long screenLeftTime, long screenRightTime,
                                        long currentTime) {
                currentTimeTv.setText(zeroTimeFormat.format(currentTime));
            }
        });

        //刻度条缩放监听
        mTimebarView.setOnBarScaledListener(new TimebarView.OnBarScaledListener() {
            @Override
            public void onOnBarScaledMode(int mode) {
                //返回缩放级别
                Log.d(TAG, "onOnBarScaledMode()" + mode);
            }

            @Override
            public void onBarScaled(long screenLeftTime, long screenRightTime, long currentTime) {
                currentTimeTv.setText(zeroTimeFormat.format(currentTime));
                Log.d(TAG, "onBarScaled()");
            }

            @Override
            public void onBarScaleFinish(long screenLeftTime, long screenRightTime,
                                         long currentTime) {
                Log.d(TAG, "onBarScaleFinish()");
            }
        });


        seekProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //进度已经被修改
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (isTouchSeeked) {
                    seekProgress.showSeekDialog(makeTimeString(progress));
                } else {
                    seekProgress.hideSeekDialog();
                }
            }

            //已经开始一个触摸拖动手势
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
//                showControlView(3600000);
                isTouchSeeked = true;
            }

            //触摸拖动手势结束
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Message msg = Message.obtain();
                msg.what = PROGRESS_SEEEKTO;
                msg.arg1 = seekProgress.getProgress();
                mHandler.removeMessages(PROGRESS_SEEEKTO);
                mHandler.sendMessageAtTime(msg, 1000);
                isTouchSeeked = false;
//                showControlView(sDefaultTimeout);
            }
        });
    }

    private StringBuilder sb = new StringBuilder();
    private Formatter formatter = new Formatter(sb, Locale.getDefault());
    private final Object[] sTimeArgs = new Object[3];

    private String makeTimeString(int secs) {
        String durationformat = "HH:mm:ss";
        sb.setLength(0);
        secs = secs / 1000;
        Object[] timeArgs = sTimeArgs;
        timeArgs[0] = secs / 3600;//
        timeArgs[1] = (secs % 3600) / 60;
        timeArgs[1] = (secs % 3600 % 60) % 60;
        return formatter.format(durationformat, timeArgs).toString().trim();
    }

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case PROGRESS_SEEEKTO:
                    Log.e("ycf___", "notifyDataSetChanged");
//                    seekProgress.setProgress(1);
                    seekProgress.setProgress(100);
                    break;

            }
            return false;
        }
    });


    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        mTimebarView.recycle();
    }

    @Override
    public void onBackPressed() {
///       不需要回归竖屏
//        if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//            videoPlayer.getFullscreenButton().performClick();
//            return;
//        }
        //释放所有
        videoPlayer.setVideoAllCallBack(null);
        super.onBackPressed();
    }

    @OnClick({R.id.timebar_zoom_out_btn, R.id.timebar_zoom_in_btn, R.id.day, R.id.hour,
            R.id.minute})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.timebar_zoom_out_btn:
                mTimebarView.scaleByPressingButton(false);
                break;
            case R.id.timebar_zoom_in_btn:
                mTimebarView.scaleByPressingButton(true);
                break;
            case R.id.day:
                mTimebarView.setMode(3);
                break;
            case R.id.hour:
                mTimebarView.setMode(2);
                break;
            case R.id.minute:
                mTimebarView.setMode(1);
                break;
        }

//        f(0) = x; s=0;
//        f(1) = x + (f(0)*5*0.9); s=1;
//        f(2) = x + (f(0)*5*0.9) + (f(1)*5*0.8); s=2;
//        f(3) = x + (f(0)*5*0.9) + (f(1)*5*0.8) + (f(2)*5*0.7); s=3;
//        f(4) = x + (f(0)*5*0.9) + (f(1)*5*0.8) + (f(2)*5*0.7) + (f(3)*5*0.6); s=4;
//        f(5) = x + (f(0)*5*0.9) + (f(1)*5*0.8) + (f(2)*5*0.7) + (f(3)*5*0.6) + (f(4)*5*0.6); s=5;
//
//        f(0) = s; x=0;
//        f(1) = (f(0)*5*0.9); x=1;
//        f(2) = (f(1)*5*0.8); x=2;
//        f(3) = (f(2)*5*0.7); x=3;
//        f(4) = (f(3)*5*0.6); x=4;
//        f(5) = (f(4)*5*0.6); x=5;
//
//        f(x) = s; x=0;
//        f(x) = 5*f(x-1)*(1-x/10); x>0;
//        g(s) = f(0)+f(1)+f(2)+f(3)+f(4)+f(5);
//
//        f(0) = s; x=0;
//        f(1) = (f(0)*5*0.9)=s*5*0.9; x=1; 900
//        f(2) = (f(1)*5*0.8)=s*(5^2)*0.9*0.8; x=2; 3600
//        f(3) = (f(2)*5*0.7)=s*(5^3)*0.9*0.8*0.7; x=3; 12600
//        f(4) = (f(3)*5*0.6)=s*(5^4)*0.9*0.8*0.7*0.6; x=4;
//        f(5) = (f(4)*5*0.5)=s*(5^5)*0.9*0.8*0.7*0.6*0.5; x=5;
//        f(5) = (f(5)*5*0.4)=s*(5^5)*0.9*0.8*0.7*0.6*0.5*0.4; x=5;
//
//        f(0) = s; x=0;
//        f(1) = (f(0)*5*0.9)=s*5*(10^(-1))*9; x=1;
//        f(2) = (f(1)*5*0.8)=s*(5^2)*(10^(-2))*9*8; x=2;
//        f(3) = (f(2)*5*0.7)=s*(5^3)*(10^(-3))*9*8*7; x=3;
//        f(4) = (f(3)*5*0.6)=s*(5^4)*(10^(-4))*9*8*7*6; x=4;
//        f(5) = (f(4)*5*0.6)=s*(5^5)*(10^(-5))*9*8*7*6*5; x=5;
//
//        f(0) = s; x=0;
//        f(1) = (f(0)*5*0.9)=s*(5^1)*(10^(-5))*(10^4)*9; x=1;
//        f(2) = (f(1)*5*0.8)=s*(5^2)*(10^(-5))*(10^3)*9*8; x=2;
//        f(3) = (f(2)*5*0.7)=s*(5^3)*(10^(-5))*(10^2)*9*8*7; x=3;
//        f(4) = (f(3)*5*0.6)=s*(5^4)*(10^(-5))*(10^1)*9*8*7*6; x=4;
//        f(5) = (f(4)*5*0.6)=s*(5^5)*(10^(-5))*(10^0)*9*8*7*6*5; x=5;
//
//        f(x) = s*(5^x)*(10^(-x))*(9!)/((9-x)!); x=1~5;
//        f(x) = s*(9!)*(5^x)*(10^(-x))*(((9-x)!)^(-1)); x=1~5;
    }
}
